﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using System.Web.Mvc;
using MvcWeb.Models;
using System.IO;
using SailHero.Soft.FrameWork.IDomainRepositories.Contracts;
using SailHero.Soft.FrameWork.Models;
using UI.Web.SailHeroSoftAuthorization.Helper;

namespace MvcWeb.Controllers
{
    [Export(typeof(IController)), ExportMetadata("Name", "Auth")]
    public class AuthController : BaseController
    {
        /// <summary>
        /// 数据操作接口
        /// </summary>
        [Import]
        public ISoftAuthKeyRepository keyModel;

        [Import]
        public ISoftWareRepository SoftModel;

        [Import]
        public ISys_UserRepository userModel;

        [Authorize]
        public ActionResult Index(string page)
        {
            var list = keyModel.GetAllList();
            list = list.OrderBy(itm => itm.SOFTNO);
            int size = 10;
            if (page != null)
            {
                ViewData["page"] = PagerHelper.Pager(Request.RawUrl.Substring(0, Request.RawUrl.IndexOf("?")), Convert.ToInt32(page), list.Count(), size, 4);
                list = list.Skip((Convert.ToInt32(Request["page"]) - 1) * size).Take(size);
            }
            else
            {
                ViewData["page"] = PagerHelper.Pager(Request.RawUrl, 1, list.Count(), size, 4);
                list = list.Skip((1 - 1) * size).Take(size);
            }

            ViewBag.SoftModel = SoftModel;
            return View(list.AsEnumerable());
        }

        [Authorize]
        public ActionResult Create()
        {
            return View();
        }

        [Authorize]
        public ActionResult VMCode()
        {
            return View();
        }
        [Authorize]
        public ActionResult VSkey()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                SYS_SOFTAUTHKEY mod = new SYS_SOFTAUTHKEY();
                mod.ID = DateTime.Now.Ticks.ToString();
                mod.SOFTID = Request.Form["SoftID"];
                mod.SOFTNO = Request.Form["SoftNo"];
                mod.SOFTVERSION = Request.Form["SoftVersion"];
                mod.WPLACE = Request.Form["WPlace"];
                mod.SKEYFILE = Request.Form["SKeyFile"];
                mod.MCODEFILE = Request.Form["MCodeFile"];
                mod.MACHINECODE = Request.Form["MachineCode"];
                mod.CREATOR = LoginUser.USERCNAME;
                mod.CREATEDATE = DateTime.Now;
                mod.MAC = Request.Form["MAC"];
                mod.CPUID = Request.Form["CPUID"];
                mod.DETAILPLACE = Request.Form["DetailPlace"];
                mod.CUSTOMER = Request.Form["Customer"];
                mod.SKEYFILE = GenerateSkey(mod.SOFTID, mod.MACHINECODE);
                keyModel.Add(mod);
                keyModel.UnitOfWork.SaveChanges();
                Response.Redirect(@"/Auth/Index");
                return View();

            }
            catch (Exception ee)
            {
                ViewData["softList"] = new SelectList(keyModel.GetAllList(), "ID", "WPlace");
                return View();
            }
        }

        private string GenerateSkey(string SoftID, string MachineCode)
        {
            try
            {
                IntPtr intPtr0 = AuthCode.GenerateKey(new StringBuilder(SoftID), new StringBuilder(MachineCode));
                string str0 = Marshal.PtrToStringAuto(intPtr0);

                PathHelper helper = new PathHelper();
                string str1 = helper.GetLocalPath() + str0.Replace(@"\",@"/");

                return str1;
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        [Authorize]
        public ActionResult Edit(string id)
        {
            SYS_SOFTAUTHKEY mod = keyModel.Get(id);
            return View(mod);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Edit(string id, FormCollection collection)
        {
            SYS_SOFTAUTHKEY mod = keyModel.Get(id);
            try
            {
                mod.SOFTID = Request.Form["SoftID"];
                mod.SOFTNO = Request.Form["SoftNo"];
                mod.SOFTVERSION = Request.Form["SoftVersion"];
                mod.WPLACE = Request.Form["WPlace"];
                mod.SKEYFILE = Request.Form["SKeyFile"];
                mod.MCODEFILE = Request.Form["MCodeFile"];
                mod.MACHINECODE = Request.Form["MachineCode"];
                mod.MAC = Request.Form["MAC"];
                mod.CPUID = Request.Form["CPUID"];
                mod.UPDATEUSER = LoginUser.USERCNAME;
                mod.UPDATEDATE = DateTime.Now;
                mod.DETAILPLACE = Request.Form["DetailPlace"];
                mod.CUSTOMER = Request.Form["Customer"];
                keyModel.UnitOfWork.SaveChanges();
                return RedirectToAction("Index");
            }
            catch (Exception ee)
            {
                ViewData["softList"] = new SelectList(keyModel.GetAllList(), "ID", "WPlace");
                return View(mod);
            }
        }

        [Authorize]
        [HttpPost]
        public string Delete(string ID)
        {

            try
            {
                // TODO: Add delete logic here
                keyModel.Delete(itm => itm.ID == ID);
                keyModel.UnitOfWork.SaveChanges();
                return "success";
            }
            catch
            {
                return "fail";
            }

        }


        [HttpPost]
        public void UploadSkey()
        {
            string uploadPath = new PathHelper().GetLocalPath()+"/Upload/";

            string filename = string.Empty;
            string tmpPath = Server.MapPath(uploadPath);
            try
            {
                if (Request.Files["fileToUpload"] != null)
                {

                    filename = Request.Files["fileToUpload"].FileName;
                    if (filename.LastIndexOf("\\") > 0)
                    {
                        filename = filename.Substring(filename.LastIndexOf("\\")).Replace("\\", "");
                    }
                    Stream st = Request.Files["fileToUpload"].InputStream;
                    int size = 0;
                    StreamToFile(st, tmpPath + filename, out size);
                }

                string theFile;
                theFile = tmpPath + filename;
                try
                {
                    if (!System.IO.File.Exists(theFile))
                    {
                        Response.Clear();
                        Response.Write(@"{
                            status : 'error',
                            msg : '文件不存在'
                            }");
                        Response.End();
                        return;
                    }
                    IntPtr intPtr = AuthCode.VerifiKeyOnly(new StringBuilder(theFile));
                    string str = Marshal.PtrToStringAuto(intPtr);

                    if (string.IsNullOrEmpty(str) || str == "no")
                    {
                        Response.Clear();
                        Response.Write(@"{
                            status : 'error',
                            msg : '验证失败'
                            }");
                        Response.End();
                        return;
                    }
                    else
                    {
                        Response.Clear();
                        string[] cts = str.Split('|');
                        string SoftId = "";
                        string SoftCName = "";
                        SYS_SOFTWARE mdl = SoftModel.FirstOrDefault(itm => itm.SOFTNO == cts[3]);
                        if (mdl == null)
                        {
                            Response.Clear();
                            Response.Write(@"{
                            status : 'error',
                            msg : '软件标识编号错误：标识为：" + cts[3] + @"'
                            }");
                            Response.End();
                            return;
                        }
                        SoftId = mdl.ID;
                        SoftCName = mdl.SOFTCNAME;
                        Response.Write(@"{
                                status : 'success',msg:'通过验证',MachinCode:'" + cts[0] +
                                    "',CPUID:'" + cts[1] +
                                    "',MAC:'" + cts[2] +
                                    "',ProductId:'" + cts[3] +
                                    "',Version:'" + cts[4] +
                                    "',McodeFile:'" + uploadPath + "/" + filename +
                                    "',SkeyFile:'等待生成" +
                                    "',SoftID:'" + SoftId +
                                    "',SoftCName:'" + SoftCName +
                                    "'}");
                        Response.End();
                        return;
                    }


                }
                catch (Exception ex)
                {
                    Response.Clear();
                    Response.Write(@"{
                        status : 'error',
                        msg : '" + ex.Message + @"'
                        }");
                    Response.End();
                }
                finally
                {

                }
            }
            catch (Exception ex)
            {
                Response.Clear();
                Response.Write(@"{
                status : 'error',
                msg : '" + ex.Message + @"'
                }");
                Response.End();
            }
        }

        [HttpPost]
        public void UploadMatch()
        {
            string uploadPath = new PathHelper().GetLocalPath()+"/Upload/";

            string filename = string.Empty;
            string tmpPath = Server.MapPath(uploadPath);
            try
            {
                if (Request.Files["fileToUpload"] != null)
                {

                    filename = Request.Files["fileToUpload"].FileName;
                    if (filename.LastIndexOf("\\") > 0)
                    {
                        filename = filename.Substring(filename.LastIndexOf("\\")).Replace("\\", "");
                    }
                    Stream st = Request.Files["fileToUpload"].InputStream;
                    int size = 0;
                    StreamToFile(st, tmpPath + filename, out size);
                }

                string theFile;
                theFile = tmpPath + filename;
                try
                {
                    if (!System.IO.File.Exists(theFile))
                    {
                        Response.Clear();
                        Response.Write(@"{
                            status : 'error',
                            msg : '文件不存在'
                            }");
                        Response.End();
                        return;
                    }
                    IntPtr intPtr = AuthCode.VerifiKeyOnly(new StringBuilder(theFile));
                    string str = Marshal.PtrToStringAuto(intPtr);

                    if (string.IsNullOrEmpty(str) || str == "no")
                    {
                        Response.Clear();
                        Response.Write(@"{
                            status : 'error',
                            msg : '验证失败'
                            }");
                        Response.End();
                        return;
                    }
                    else
                    {
                        Response.Clear();
                        string[] cts = str.Split('|');
                        string SoftId = "";
                        string SoftCName = "";
                        SYS_SOFTWARE mdl = SoftModel.FirstOrDefault(itm => itm.SOFTNO == cts[3]);
                        if (mdl == null)
                        {
                            Response.Clear();
                            Response.Write(@"{
                            status : 'error',
                            msg : '软件标识编号错误：标识为：" + cts[2] + @"'
                            }");
                            Response.End();
                            return;
                        }
                        SoftId = mdl.ID;
                        SoftCName = mdl.SOFTCNAME;
                        Response.Write(@"{
                                status : 'success',msg:'通过验证',MachinCode:'" + cts[0] +
                                    "',CPUID:'" + cts[1] +
                                    "',MAC:'" + cts[2] +
                                    "',ProductId:'" + cts[3] +
                                    "',Version:'" + cts[4] +
                                    "',McodeFile:'" + uploadPath + filename +
                                    "',SkeyFile:'等待生成" +
                                    "',SoftID:'" + SoftId +
                                    "',SoftCName:'" + SoftCName +
                                    "'}");
                        Response.End();
                        return;
                    }


                }
                catch (Exception ex)
                {
                    Response.Clear();
                    Response.Write(@"{
                        status : 'error',
                        msg : '" + ex.Message + @"'
                        }");
                    Response.End();
                }
                finally
                {

                }
            }
            catch (Exception ex)
            {
                Response.Clear();
                Response.Write(@"{
                status : 'error',
                msg : '" + ex.Message + @"'
                }");
                Response.End();
            }
        }


        [HttpPost]
        public void Upload()
        {
            
            string uploadPath = new PathHelper().GetLocalPath()+"/Upload/";

            string filename = string.Empty;
            string tmpPath = Server.MapPath(uploadPath);
            try
            {
                if (Request.Files["fileToUpload"] != null)
                {

                    filename = Request.Files["fileToUpload"].FileName;
                    if (filename.LastIndexOf("\\") > 0)
                    {
                        filename = filename.Substring(filename.LastIndexOf("\\")).Replace("\\", "");
                    }
                    Stream st = Request.Files["fileToUpload"].InputStream;
                    int size = 0;
                    StreamToFile(st, tmpPath + filename, out size);
                }

                string theFile;
                StreamReader reader = null;
                FileStream fs = null;
                theFile = tmpPath + filename;
                try
                {
                    if (!System.IO.File.Exists(theFile))
                    {
                        Response.Clear();
                        Response.Write(@"{
                            status : 'error',
                            msg : '文件不存在'
                            }");
                        Response.End();
                        return;
                    }
                    IntPtr intPtr = AuthCode.VerifiMachineKey(new StringBuilder(theFile));
                    string str = Marshal.PtrToStringAuto(intPtr);

                    if (string.IsNullOrEmpty(str) || str == "no")
                    {
                        Response.Clear();
                        Response.Write(@"{
                            status : 'error',
                            msg : '验证失败'
                            }");
                        Response.End();
                        return;
                    }
                    else
                    {
                        fs = new FileStream(theFile, FileMode.Open);
                        reader = new StreamReader(fs);
                        string machincode = reader.ReadToEnd();
                        Response.Clear();
                        string[] cts = str.Split('|');
                        string SoftId = "";
                        string SoftCName = "";
                        string Sno = cts[2];
                        SYS_SOFTWARE mdl = SoftModel.FirstOrDefault(itm => itm.SOFTNO == Sno);
                        if (mdl == null)
                        {
                            Response.Clear();
                            Response.Write(@"{
                            status : 'error',
                            msg : '软件标识编号错误：标识为：" + cts[2] + @"'
                            }");
                            Response.End();
                            return;
                        }
                        SoftId = mdl.ID;
                        SoftCName = mdl.SOFTCNAME;
                        Response.Write(@"{
                                status : 'success',msg:'通过验证',MachinCode:'" + machincode +
                                    "',CPUID:'" + cts[0] +
                                    "',MAC:'" + cts[1] +
                                    "',ProductId:'" + cts[2] +
                                    "',Version:'" + cts[3] +
                                    "',McodeFile:'" + uploadPath + filename +
                                    "',SkeyFile:'等待生成" +
                                    "',SoftID:'" + SoftId +
                                    "',SoftCName:'" + SoftCName +
                                    "'}");
                        Response.End();
                        reader.Close();
                        fs.Close();
                        return;
                    }


                }
                catch (Exception ex)
                {
                    Response.Clear();
                    Response.Write(@"{
                        status : 'error',
                        msg : '" + ex.Message + @"'
                        }");
                    Response.End();
                }
                finally
                {
                    if (reader != null) reader.Close();
                    if (fs != null) fs.Close();
                }
            }
            catch (Exception ex)
            {
                Response.Clear();
                Response.Write(@"{
                status : 'error',
                msg : '" + ex.Message + @"'
                }");
                Response.End();
            }
        }

        /// <summary> 
        ///  
        /// </summary> 
        /* - - - - - - - - - - - - - - - - - - - - - - - - 
        * Stream 和 文件之间的转换 
        * - - - - - - - - - - - - - - - - - - - - - - - */
        /// <summary>
        /// 将 Stream 写入文件
        /// </summary>
        /// <param name="stream">传入的Stream流对象</param>
        /// <param name="fileName">要存储的完整路径文件名</param>
        /// <param name="fileSize">文件大小</param>
        public static void StreamToFile(Stream stream, string fileName, out int fileSize)
        {
            FileStream fs, targetStream;

            //文件流传输
            using (targetStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
            {
                //定义文件缓冲区
                const int bufferLen = 4096;
                byte[] buffer = new byte[bufferLen];
                int count = 0;

                while ((count = stream.Read(buffer, 0, bufferLen)) > 0)
                {
                    targetStream.Write(buffer, 0, count);
                }
                fileSize = (int)targetStream.Length;
                targetStream.Close();
                stream.Close();
            }
        }
    }
}
